import pubsub_pb2
import pubsub_pb2_grpc

from concurrent import futures
import time
import threading

import grpc
import google.protobuf.empty_pb2 as empty_pb2


_ONE_DAY_IN_SECONDS = 60 * 60 * 24


class MasterServicerImpl(pubsub_pb2_grpc.MasterServicer):
    def registerPublisher(self, request, context):
        print("in registerPublisher")
        return empty_pb2.Empty()
    def registerSubscriber(self, request, context):
        print("in registerSubscriber")
        return empty_pb2.Empty()

        # print(request.req)
        # return pubsub_pb2.pubsubResponse(res=request.req)

class MasterSlaveServicerImpl(pubsub_pb2_grpc.MasterSlaveServicer):
    def pubUpdate(self, request, context):
        print("in pubUpdate")
        return empty_pb2.Empty()
        
class PublisherServicerImpl(pubsub_pb2_grpc.PublisherServicer):
    def Publish(self, request, context):
        print("in Publish")
        return empty_pb2.Empty()


def serveMasterServicer(url):
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    pubsub_pb2_grpc.add_MasterServicer_to_server (
        MasterServicerImpl(), server)
    # server.add_insecure_port('[::]:50051')
    server.add_insecure_port(url)
    server.start()
    try:
        while True:
            time.sleep(_ONE_DAY_IN_SECONDS)
    except KeyboardInterrupt:
        server.stop(0)
def serveMasterSlaveServicer(url):
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    pubsub_pb2_grpc.add_MasterSlaveServicer_to_server (
        MasterSlaveServicerImpl(), server)
    # server.add_insecure_port('[::]:50051')
    server.add_insecure_port(url)
    server.start()
    try:
        while True:
            time.sleep(_ONE_DAY_IN_SECONDS)
    except KeyboardInterrupt:
        server.stop(0)
def servePublisherServicer(url):
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    pubsub_pb2_grpc.add_PublisherServicer_to_server (
        PublisherServicerImpl(), server)
    # server.add_insecure_port('[::]:50051')
    server.add_insecure_port(url)
    server.start()
    try:
        while True:
            time.sleep(_ONE_DAY_IN_SECONDS)
    except KeyboardInterrupt:
        server.stop(0)


if __name__ == '__main__':
    # serve()
    t1 = threading.Thread(target=serveMasterServicer, args=('[::]:50051',))
    t2 = threading.Thread(target=serveMasterSlaveServicer, args=('[::]:50052',))
    t3 = threading.Thread(target=servePublisherServicer, args=('[::]:50053',))
    t1.start()
    t2.start()
    t3.start()
    t1.join()
    t2.join()
    t3.join()
